import { Injectable } from '@nestjs/common';
import { EncryptedDataType, LoginDto, RegisterDto } from './dto/user.dto';
import { GlobalRsaKeyPairService } from '@/modules/global-module/rsa-key-pair/service';
import { generateResponse, GenerateResponseParams } from '@/utils/response';
import { importKeyFromJWK, decryptData } from '@/utils/decrypt';
import { decryptWithPrivateKey } from '@/middleware/rsa-key-pair';

@Injectable()
export class UserService {
  constructor(private readonly globalRsaKeyPairService: GlobalRsaKeyPairService) {}

  getToken() {
    return 'token';
  }

  /**
   * 解密数据
   * @param encryptedKey 加密的AES密钥
   * @param encryptedData 加密的数据
   * @returns 解密后的数据
   */
  private async getDecryptData(encryptedKey: string, encryptedData: EncryptedDataType) {
    // 取到RSA私钥
    const rsaPrivateKey = this.globalRsaKeyPairService.getRsaPrivateKey();
    // 用私钥解密AES密钥，并将AES密钥从JWK格式转为原始格式
    const key = await importKeyFromJWK(decryptWithPrivateKey(encryptedKey, rsaPrivateKey));
    return await decryptData(encryptedData.encrypted, encryptedData.iv, key);
  }

  /**
   * 登录
   * @param loginDto
   * @returns
   */
  async login(loginDto: LoginDto): Promise<
    GenerateResponseParams<{
      decryptAccount: string;
      decryptPassword: string;
    }>
  > {
    const { key: encryptedKey, account, password } = loginDto;
    const decryptAccount = await this.getDecryptData(encryptedKey, account);
    const decryptPassword = await this.getDecryptData(encryptedKey, password);
    return generateResponse({
      data: {
        decryptAccount,
        decryptPassword,
      },
    });
  }

  /**
   * 注册
   * @param registerDto
   * @returns
   */
  async signUp(registerDto: RegisterDto) {
    const { key: encryptedKey, account, password, username, email } = registerDto;
    const decryptAccount = await this.getDecryptData(encryptedKey, account);
    const decryptPassword = await this.getDecryptData(encryptedKey, password);
    const decryptEmail = await this.getDecryptData(encryptedKey, email);
    return 'register';
  }
}
